from rest_framework import serializers
import re
from rest_framework.authentication import authenticate
from rest_framework_jwt.serializers import jwt_encode_handler,jwt_payload_handler
from django.core.cache import cache
from . import models
from django.conf import settings



#验证多方式登录接口
class LoginModelSerializer(serializers.ModelSerializer):
    username = serializers.CharField(write_only=True)
    password = serializers.CharField(write_only=True)
    class Meta:
        model = models.User
        fields = ['username','password']
    def validate(self, attrs):

        user = self._many_method_login(attrs)
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        self.user = user
        self.token = token
        return attrs
    def _many_method_login(self,attrs):
        username = attrs.get('username')
        password = attrs.get('password')
        if re.match(r'.*@.*',username):
            user = models.User.objects.filter(email=username).first()
        elif re.match(r'^1[3-9][0-9]{9}]$',username):
            user = models.User.objects.filter(mobile=username)
        else:
            user = models.User.objects.filter(username=username).first()
        if not user:
            return serializers.ValidationError('用户名不存在')
        if not user.check_password(password):
            return serializers.ValidationError('密码错误')
        return user



#手机验证登录接口

    '''
        获取手机号 验证码 校验手机号格式  验证码与缓存验证码进行比对 是否符合
        
        登录时验证手机号已经注册 
        
        
    '''

class MobileLoginModelSerializer(serializers.ModelSerializer):
    mobile = serializers.CharField(min_length=11,max_length=11,write_only=True)
    code = serializers.CharField(min_length=4,max_length=4,write_only=True)

    class Meta:
        model = models.User
        fields = ['mobile','code']

    def validate_mobile(self, value):
        if not(value and re.match(r'^1[3-9][0-9]{9}$',value)):
            return serializers.ValidationError('手机号格式错误')
        return value

    def validate(self, attrs):
        mobile = attrs.get('mobile')
        code = attrs.get('code')
        cache_code = cache.get(settings.CHECK_PREFIX_KEY % mobile)
        if code != cache_code:
            raise serializers.ValidationError('验证码错误')
        user_obj = models.User.objects.filter(mobile=mobile).first()
        payload = jwt_payload_handler(user_obj)
        token = jwt_encode_handler(payload)
        self.user = user_obj
        self.token = token
        return attrs



'''
    手机注册接口
        手机
        验证验证码 
        密码
        验证手机是否可以进行注册
        密码是否符合格式
        创建用户
        create_user
'''



# class RegisterModelSerializer(serializers.ModelSerializer):
#     code = serializers.CharField(min_length=4,max_length=4,write_only=True)
#
#     class Meta:
#         model = models.User
#         fields = ['mobile','code','password']
#
#     def validate_mobile(self,value):
#         if not (value and re.match(r'^1[3-9][0-9]{9}$', value)):
#             raise serializers.ValidationError({'mobile':'手机号格式不正确'})
#         if models.User.objects.filter(mobile=value).first():
#             print(value)
#             raise serializers.ValidationError({'mobile':'手机号已经注册'})
#         return value
#
#     def validate(self, attrs):
#         mobile = attrs.get('mobile')
#         code = attrs.get('code')
#         password = attrs.get('password')
#
#         # cache_code = cache.get(settings.CHECK_PREFIX_KEY % mobile)
#         # if code != cache_code:
#         #     raise serializers.ValidationError('验证码错误')
#         # models.User.objects.create_user(**attrs)
#         print(mobile)
#         attrs['username'] = mobile
#         attrs['email'] = mobile + '@luffy.com'
#         return attrs
#
#
#
#     def create(self, validated_data):
#         # print(**validated_data)
#         return models.User.objects.create_user(**validated_data)
# 手机验证码注册
class RegisterMobileSerializer(serializers.ModelSerializer):
    code = serializers.CharField(write_only=True, min_length=4, max_length=4)
    class Meta:
        model = models.User
        fields = ('mobile', 'code', 'password')
        extra_kwargs = {
            'mobile': {
                'min_length': 11,
                'max_length': 11
            },
            'password': {
                'min_length': 6,
                'max_length': 18
            },
        }

    def validate_mobile(self, value):
        if re.match(r'^1[3-9][0-9]{9}$', value):
            return value
        raise serializers.ValidationError('手机号格式有误')

    def validate_code(self, value):
        print(value)
        try:
            int(value)
            return value
        except:
            raise serializers.ValidationError('验证码格式有误')

    def validate_password(self, value):
        # 密码不能包含或必须包含哪些字符
        return value

    # 拿出不入库的数据，塞入额外要入库的数据
    def validate(self, attrs):
        mobile = attrs.get('mobile')
        code = attrs.pop('code')
        old_code = cache.get(settings.CHECK_PREFIX_KEY % mobile)
        print(old_code)
        if code != old_code:
            raise serializers.ValidationError({'code': '验证码有误'})
        # cache.set(settings.SMS_CACHE_KEY % mobile, '0000', 0)  # 清除一次性验证码

        attrs['username'] = mobile
        attrs['email'] = '%s@oldboy.com' % mobile

        return attrs

    # User表必须重写create方法，才能操作密文密码
    def create(self, validated_data):
        return models.User.objects.create_user(**validated_data)










